package org.tity.commons.network;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.tity.commons.log.Logger;

import com.alibaba.fastjson.JSONObject;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Ajax {
	
	public static OkHttpClient client = null;
	
	private static void initClientIf()
	{
		if(client!=null) return;
		client = new OkHttpClient.Builder().readTimeout(120, TimeUnit.SECONDS).build();
	}
	
	private static Map<String,String> COOIKES=null;
	
	public static void setCookies(Map<String,String> cooikes)
	{
		COOIKES=cooikes;
	}
	

	public static String get(String url)
	{
		initClientIf();
		Request.Builder builder = new Request.Builder().url(url).get();
        
        if(COOIKES!=null) {
 			String cookieValue="";
 			for (String name : COOIKES.keySet()) {
 				cookieValue+=name+"="+COOIKES.get(name)+"; ";
			}
 			if(cookieValue.length()>0) {
 				cookieValue=cookieValue.substring(0,cookieValue.length()-2);
 			}
 			
 			builder.addHeader("Cookie", cookieValue);
 		}
        
        Request request=builder.build();
        
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            Logger.exception(e);
            return null;
        }
 
	}
 
	public static String post(String url)
	{
		return post(url,new HashMap<String, Object>(),MediaType.parse("application/text; charset=utf-8"));
	}
	
	public static String post(String url,Map<String, Object> params)
	{
		return post(url,params,MediaType.parse("application/text; charset=utf-8"));
	}
	
	public static String post(String url,Map<String, Object> params,String mediaType)
	{
		return post(url,params,MediaType.parse(mediaType));
	}
	
	public static String post(String url,Map<String,Object> params,MediaType mediaType)
	{
		initClientIf();
		RequestBody requestBody = null;
		try {
			requestBody = FormBody.create(mediaType, JSONObject.toJSONString(params));
			Request request = new Request.Builder().url(url).post(requestBody).build();
			Response response = client.newCall(request).execute();
			String jsonstr=response.body().string();
			if(jsonstr==null || jsonstr.length()==0 || jsonstr.startsWith("<")) {
				Logger.error("服务调用异常");
				Logger.error(url);
				return null;
			} else {
				return jsonstr;
			}
		} catch(Exception e) {
			Logger.exception("服务调用异常",e);
			Logger.error(url);
			return null;
		}
	}
   

}
